﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Framework.Comum.Pesquisa;
using NaviCar.Servico.Entidades;
using System.Web.Helpers;
using System.Data;
using NaviCar.DB.Repositorio;
using System.Collections.Specialized;
using System.IO;
using System.Text;
using Framework.Comum.DAL;

namespace NaviCar.Controllers
{
    [SessionState(System.Web.SessionState.SessionStateBehavior.Required)]
    public class BaseController: Controller 
    {
        protected override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            base.OnActionExecuting(filterContext);
        }

        protected override void OnResultExecuted(ResultExecutedContext filterContext)
        {
            base.OnResultExecuted(filterContext);

            IGerenciadorContexto contexto = ConfiguradorRepositorio.GerenciadorDB();

            if(contexto != null)  contexto.LiberarInstacia();
        }
        
        public string ViewAsString(string nomeView, object model, Dictionary<string, object> valoresViewData)
        {
            StringWriter sw = default(StringWriter);
            StringBuilder sb = new StringBuilder();

            sw = new StringWriter(sb);

            ViewEngineResult result = ViewEngines.Engines.FindView(ControllerContext, nomeView, "");

            ViewDataDictionary dicionarioViewDataDictionary = new ViewDataDictionary(model);
            TempDataDictionary tempData = new TempDataDictionary();

            if ((valoresViewData != null))
            {
                foreach (string chave in valoresViewData.Keys)
                {
                    dicionarioViewDataDictionary.Add(chave, valoresViewData[chave]);
                }
            }

            this.ViewData.Model = model;

            ViewContext viewContext = new ViewContext(ControllerContext, result.View, dicionarioViewDataDictionary, tempData, sw);

            result.View.Render(viewContext, sw);

            return sb.ToString();

        }


    }
}
